import json

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

# Create your views here.
from django_redis import get_redis_connection
from haystack.query import SearchQuerySet

from goods.models import GoodsCategory, SKU
from goods.utils import get_breadcrumb
from meiduo_mall.utils.mixins import LoginRequiredMixin


class SKUListView(View):
    @staticmethod
    def get(request, category_id):
        """分类商品数据获取"""
        page = request.GET.get('page', 1)
        page_size = request.GET.get('page_size', 10)
        ordering = request.GET.get('ordering', '-create_time')

        try:
            cat3 = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400,
                                 'message': '分类数据不存在'})

        try:
            breadcrumb = get_breadcrumb(cat3)
        except Exception:
            return JsonResponse({'code': 400,
                                 'message': '面包屑导航数据获取错误'})

        try:
            skus = SKU.objects.filter(category_id=category_id,
                                      is_launched=True).order_by(ordering)
        except Exception:
            return JsonResponse({'code': 400,
                                 'message': '分类SKU商品数据获取错误'})

        paginator = Paginator(skus, page_size)
        results = paginator.get_page(page)

        sku_li = []
        nginx_url = 'http://192.168.19.131:8888/'
        
        for sku in results:
            sku_li.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'comments': sku.comments,
                'default_image_url': ''.join([nginx_url,sku.default_image.name])
            })

        return JsonResponse({
            'code': 0,
            'message': 'OK',
            'breadcrumb': breadcrumb,
            'count': paginator.num_pages,
            'list': sku_li
        })


class HotGoodsView(View):
    @staticmethod
    def get(request, category_id):
        try:
            skus = SKU.objects.filter(category_id=category_id,
                                      is_launched=True).order_by('-sales')[:2]
        except Exception:
            return JsonResponse({'code': 400,
                                 'message': '分类SKU商品数据获取错误'})

        sku_li = []
        nginx_url = 'http://192.168.19.131:8888/'

        for sku in skus:
            sku_li.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': ''.join([nginx_url, sku.default_image.name])
            })
        return JsonResponse({
            'code': 0,
            'message': 'OK',
            'hot_skus': sku_li
        })


class SKUSearchView(View):
    @staticmethod
    def get(request):
        """SKU商品数据搜索"""
        # ① 获取参数并进行校验
        keyword = request.GET.get('q')
        page = request.GET.get('page', 1)
        page_size = request.GET.get('page_size', 6)

        if not keyword:
            return JsonResponse({'code': 400,
                                 'message': '缺少搜索关键字!'})

        # 创建搜索对象
        query = SearchQuerySet()
        search_res = query.auto_query(keyword).load_all()

        paginator = Paginator(search_res, page_size)
        results = paginator.get_page(page)

        # 组织响应数据并返回
        sku_li = []
        nginx_url = 'http://192.168.19.131:8888/'

        for res in results:
            sku = res.object
            sku_li.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': nginx_url + sku.default_image.name,
                'comments': sku.comments
            })

        return JsonResponse({'code': 0,
                             'message': 'OK',
                             'count': paginator.count,
                             'page_size': paginator.per_page,
                             'query': keyword,
                             'skus': sku_li})


class BrowseHistoryView(LoginRequiredMixin, View):
    @staticmethod
    def post(request):
        user = request.user
        # ① 获取参数并进行校验
        req_data = json.loads(request.body.decode())
        sku_id = req_data.get('sku_id')

        if not sku_id:
            return JsonResponse({'code': 400,
                                 'message': '缺少搜索关键字!'})

        try:
            redis_conn = get_redis_connection('browse_history')
        except Exception:
            return JsonResponse({'code': 400,
                                 'message': '连接redis失败'})
        history_key = f'history_{user.id}'
        try:
            pl = redis_conn.pipeline()
            pl.lrem(history_key, 0, sku_id)
            pl.lpush(history_key, sku_id)
            pl.ltrim(history_key, 0, 4)
            pl.execute()
        except Exception:
            return JsonResponse({'code': 400,
                                 'message': 'redis操作失败'})
        return JsonResponse({'code': 0,
                            'message': 'OK'})

    @staticmethod
    def get(request):
        user = request.user

        try:
            redis_conn = get_redis_connection('browse_history')
        except Exception:
            return JsonResponse({'code': 400,
                                 'message': '连接redis失败'})

        history_key = f'history_{user.id}'

        try:
            history_li = redis_conn.lrange(history_key, 0, 4)
        except Exception:
            return JsonResponse({'code': 400,
                                 'message': 'redis操作失败'})

        sku_li = []
        nginx_url = 'http://192.168.19.131:8888/'

        try:
            for sku_id in history_li:
                sku = SKU.objects.get(id=sku_id)
                sku_li.append({
                    'id': sku.id,
                    'name': sku.name,
                    'price': sku.price,
                    'comments': sku.comments,
                    'default_image_url': ''.join([nginx_url, sku.default_image.name])
                })

        except Exception:
            return JsonResponse({'code': 400,
                                 'message': 'redis操作失败'})


        return JsonResponse({
            'code': 0,
            'message': 'OK',
            'skus': sku_li
        })

